var answers = new Object();
var nextPage = 0;
var currentTimer = 'none';
var currentTime = 0;

// Common functions
// Time for each page in seconds. The introduction page have no timelimit.
function getPageTimeOut(page) {

	switch(page) {
		case 1:
		case 2:
		case 4:
		case 6:
		case 8:
		case 10:
			return 0;
			break;
		case 3:
			return 70;
			break;
		case 5:
			return 90;
			break;
		case 7:
			return 90;
			break;
		case 9:
			return 60;	
			break;
	}
}

// Show site "timeout"
function pageTimeout(page) {
	document.getElementById('page' + (page-1)).style.display = 'none';
	//jquery $('#page' + (page -1)).hide();
	document.getElementById('timeout').style.display = '';
	//jquery $('#timeout').show(); 
	
	//set global variable to  nextPage
	nextPage = page;
}

// Hide site "timeout" and display next page
function continueAfterTimeout() {
	document.getElementById('timeout').style.display = 'none';
	//$("#timeout").hide();
	displayCanvasPage(nextPage);
}

// Get the innerHTML for the timer 
function getTimerDisplayVal(secondVal) {
	var displaySeconds = secondVal % 60;
	var displayMinutes = Math.floor(secondVal / 60);
	var displayString = 'Verbleibende Zeit: ' + displayMinutes + ':' + (displaySeconds < 10 ? '0' : '') + displaySeconds;
	return displayString;
}

// Display the timer on the right top of the application
function insertTimer(page, timeVal) {
	currentTime = timeVal;
	var html = '<div style="position:absolute; top:0px;right:0px" class="timerframe">'
	html += '<span style="font-size: 1.2em" id="displaytimer_' + page + '" class="displaytimer">' + getTimerDisplayVal(currentTime) + '</span></div>';
	var mainHTML = document.getElementById('page' + page) .innerHTML;
	html += mainHTML;
	document.getElementById('page' + page).innerHTML = html;
	//$('#page' + page).prepend(html);
	
	currentTimer = setTimeout("updateTimer(" + page +")", 1000);
}

// countdown the timer
function updateTimer(page) {
	if (currentTime == 1) {
		pageTimeout(page+1);
	} else {
		document.getElementById('displaytimer_' + page).innerHTML = getTimerDisplayVal(currentTime--);
		currentTimer = setTimeout("updateTimer(" + page +")", 1000);
	}

}


// Canvas specific functions

//Init the Canvas view with the viewer and owner data
function initCanvas() {
	
	var req_objects = new Array();
	req_objects[0] = 'viewer';
	req_objects[1] = 'owner';
	
	loadCanvasData(req_objects);
	displayCanvasPage(1);
}


// Manage the Canvas sites
function displayCanvasPage(page) {
	saveCanvasPageData(page - 1);
	if (page > 1) {
		if (currentTimer != 'none') {
			clearTimeout(currentTimer);	
		}	
		var currentPageTimeout = getPageTimeOut(page);
		if (currentPageTimeout > 0) {
			insertTimer(page, currentPageTimeout);
		}
		document.getElementById('page' + (page-1)).style.display = 'none';
	}
	document.getElementById('page' + page).style.display = '';
	//$('#page' + page).show();
	
	if (typeof gadgets.window.adjustHeight() != "undefined") {
		gadgets.window.adjustHeight();
  	}
}

// hide last page and post the result to the opensocial api
function finishTest() {

	//hide last Page, here it is page10
	document.getElementById('page10').style.display = 'none';
	//jquery $('.page').hide();
	
	//TODO display loading page, hide in onFinishTest
	
	var params = {};
	
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(answers);
	
	gadgets.io.makeRequest('http://apps.azubister.net/azubister_basistest_01/results.php', onGetResults, params);
}


// get results from a remote Server
// you can also put the results into the javascript, but the apsirant could see the javasxcript file
function onGetResults(data) {
	
	var req = opensocial.newDataRequest();
	var result = new Object();
	result['azubister'] = new Object();
	result['custom'] = new Object();
	
	resultDataObject = gadgets.json.parse(data.data);
	
	result['azubister']['totals'] = resultDataObject.correct + '/' + resultDataObject.total;
	result['azubister']['success'] = resultDataObject.passed;
		
  	var jsonResult = gadgets.json.stringify(result);
  	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'azubisterTestResults', jsonResult));
	req.send();
	
	req = opensocial.newDataRequest();
	var jsonAnswers = gadgets.json.stringify(answers);
  	req.add(req.newUpdatePersonAppDataRequest(opensocial.DataRequest.PersonId.VIEWER, 'answers', jsonAnswers));
	req.send(onFinishTest);
}

// after load page
function onFinishTest(data) {
	//TODO check if write was successful
	//TODO hide loading page
	
	document.getElementById('finished').style.display = '';
	//jquery $('#finished').show();
}


/**
* Function to save the answers into object 'answers'
* For each row of an answer use an own array.
* @param page; The page wich the answers will be saved.
*/
function saveCanvasPageData(page) {
	
	switch(page) {
	
		case 3:
			answers['page3_row1'] = document.getElementById('page3_row1').value;
			answers['page3_row2'] = document.getElementById('page3_row2').value;
			answers['page3_row3'] = document.getElementById('page3_row3').value;
			answers['page3_row4'] = document.getElementById('page3_row4').value;
			// jquery answers['page3_row4'] = document.getElementById('page3_row4').val();
			break;
		case 5:
			
			j = document.page5_1.elements.length;
			for (i=0;i<j;i++) {
				if (document.page5_1.elements[i].checked) {
					answers['page5_row1'] = document.page5_1.elements[i].value;
				}
			}
			
			j = document.page5_2.elements.length;
			for (i=0;i<j;i++) {
				if (document.page5_2.elements[i].checked) {
					answers['page5_row2'] = document.page5_2.elements[i].value;
				}
			}
			break;
		case 7:
			j = document.page7_1.elements.length;
			for (i=0;i<j;i++) {
				if (document.page7_1.elements[i].checked) {
					answers['page7_row1'] = document.page7_1.elements[i].value;
				}
			}
			
			j = document.page7_2.elements.length;
			for (i=0;i<j;i++) {
				if (document.page7_2.elements[i].checked) {
					answers['page7_row2'] = document.page7_2.elements[i].value;
				}
			}
			
			j = document.page7_3.elements.length;
			for (i=0;i<j;i++) {
				if (document.page7_3.elements[i].checked) {
					answers['page7_row3'] = document.page7_3.elements[i].value;
				}
			}
			//jQuery answers['page7_row3'] = $('input[name=page7_3]:checked').val();
			break;
			
		case 9:
			j = document.page9_1.elements.length;
			for (i=0;i<j;i++) {
				if (document.page9_1.elements[i].checked) {
					answers['page9_row1'] = document.page9_1.elements[i].value;
				}
			}
			
			j = document.page9_2.elements.length;
			for (i=0;i<j;i++) {
				if (document.page9_2.elements[i].checked) {
					answers['page9_row2'] = document.page9_2.elements[i].value;
				}
			}
			
			j = document.page9_3.elements.length;
			for (i=0;i<j;i++) {
				if (document.page9_3.elements[i].checked) {
					answers['page9_row3'] = document.page9_3.elements[i].value;
				}
			}
			//jQuery answers['page9_row3'] = $('input[name=page9_3]:checked').val();
			break;
			
		default:
			break;
	}
}

// Set viewer and owner data into the HTML and adjust heigh
function onLoadCanvasData(data) {

	if (viewer = data.get('viewer')) {
		
		viewerData = viewer.getData();
		
		var name = viewerData.getField(opensocial.Person.Field.NAME); 
		document.getElementById('viewer_displayname').innerHTML = name.getField(opensocial.Name.Field.GIVEN_NAME); 
		
		
		switch (offer['type']) {
		
			case 'Ausbildung':
			case 'Schulung':
				document.getElementById('intro_offer_type').innerHTML =  'die ' + offer['type'];
				break;
			case 'Ferienjob':
				document.getElementById('intro_offer_type').innerHTML =  'der ' + offer['type'];
				break;
			case 'Praktikum':
				document.getElementById('intro_offer_type').innerHTML =  'das ' + offer['type'];
				break;
		}
		
		var gender = (viewerData.getField(opensocial.Person.Field.GENDER)).getKey();
		
		if (gender == 'MALE') {
			document.getElementById('intro_offer_job').innerHTML = 'zum ' + offer['job_name_m'];
		} else {
			document.getElementById('intro_offer_job').innerHTML = 'zur ' + offer['job_name_f'];
		}
		 	
		
		//jQuery $('.viewer_displayname').html(viewerData.getDisplayName());
	}
	
	if (owner = data.get('owner')) {
		ownerData = owner.getData();
		document.getElementById('owner_displayname').innerHTML = ownerData.getDisplayName();
		//jQuery $('.owner_displayname').html(ownerData.getDisplayName());
		document.getElementById('owner_thumbnail').src = ownerData.getField(opensocial.Person.Field.THUMBNAIL_URL);
		//jQuery $('img.owner_thumbnail').attr('src', ownerData.getField(opensocial.Person.Field.THUMBNAIL_URL));
		
		var gender = (ownerData.getField(opensocial.Person.Field.GENDER)).getKey();
		
		if (gender == 'MALE') {
			document.getElementById('intro_owner_type').innerHTML =  'einer der zuständigen Ausbilder.';
		} else {
			document.getElementById('intro_owner_type').innerHTML =  'eine der zuständigen Ausbilderinnen.';
		}
	}
 	
 	
 	
 	
 	if (typeof gadgets.window.adjustHeight() != "undefined") {
		gadgets.window.adjustHeight();
  	}
}

// load the viewer and owner data by the opensocial api
function loadCanvasData(req_objects) {

	var req = opensocial.newDataRequest();
	var opt_params = { };
	  
	opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
		opensocial.Person.Field.NAME, opensocial.Person.Field.GENDER, 'azubisterNetwork'
	];
 
	for (req_object in req_objects) {
		
		switch (req_objects[req_object]) {
			case 'viewer':
				req.add(req.newFetchPersonRequest('VIEWER', opt_params), 'viewer');
				break;
			case 'owner':
				req.add(req.newFetchPersonRequest('OWNER', opt_params), 'owner');
				break;
		
		}
	}	
	req.send(onLoadCanvasData);
}

//
// Results specific functions
//

// get Results from your own web service as ja json object
function onLoadResultData(data) {
	var params = {};
	
	testData = data.get('data').getData();	
	owner = data.get('owner').getData();;
	testDataJSON = testData[owner.getId()]['answers'];
	testDataObject = gadgets.json.parse(gadgets.util.unescapeString(testDataJSON));
	
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(testDataObject);
	
	gadgets.io.makeRequest('http://apps.azubister.net/azubister_basistest_01/results.php', onLoadResults, params);
}


function buildResultGraph(label, correct, total) {
	var html = '';	
	html += '<tr><td>' + label + '</td><td> ' + correct + '</td><td>' + total + '</td></tr>';
	return html;
}

// loaded results are shown with the google chart api
function onLoadResults(data) {
	
	resultDataObject = gadgets.json.parse(data.data);
	var resHtml = '';
	var pdata = Math.floor((resultDataObject.Zahlenreihen.correct / resultDataObject.Zahlenreihen.total) * 100);
	pdata += ',' + Math.floor((resultDataObject.Raeumlich.correct / resultDataObject.Raeumlich.total) * 100);
	pdata += ',' + Math.floor((resultDataObject.Wissen.correct / resultDataObject.Wissen.total) * 100);
	pdata += ',' + Math.floor((resultDataObject.Schaetzen.correct / resultDataObject.Schaetzen.total) * 100);
	var chl = 'Sch%C3%A4zaufgaben|Allgemeinwissen|R%C3%A4umliches+Vorstellungsverm%C3%B6gen|Zahlenreihen';
	var chxl = '1:|' + chl;
	var chm = 'tRichtig:+' + resultDataObject.Zahlenreihen.correct + ' / ' + resultDataObject.Zahlenreihen.total + ',000000,0,0,13,1';
	chm += '|tRichtig:+' + resultDataObject.Raeumlich.correct + ' / ' + resultDataObject.Raeumlich.total + ',000000,0,1,13,1';
	chm += '|tRichtig:+' + resultDataObject.Wissen.correct + ' / ' + resultDataObject.Wissen.total + ',000000,0,2,13,1';
	chm += '|tRichtig:+' + resultDataObject.Schaetzen.correct + ' / ' + resultDataObject.Schaetzen.total + ',000000,0,3,13,1';
	
	resHtml += '<img width="650" height="175" src="http://chart.apis.google.com/chart?cht=p3&chd=t:' + pdata + '&chs=650x175&chl=' + chl + '" />';
	resHtml += '<img width="500" height="175" src="http://chart.apis.google.com/chart?cht=bhg&chd=t:' + pdata + '&chs=500x175&chxt=x,y&chxl=' + chxl + '&chm=' + chm + '" />';
	
	document.getElementById('myresults').innerHTML = resHtml;
	//jquery $("#myresults").html(resHtml);
	
	if (typeof gadgets.window.adjustHeight() != "undefined") {
		gadgets.window.adjustHeight();
  	}
}

// batchRequest to get owner, annswers and azubisterTestResults
// here you can also request the custom datas.
function loadResultData() {

	var req = opensocial.newDataRequest();
	var opt_params = { };
	req.add(req.newFetchPersonRequest('OWNER', opt_params), 'owner');
	req.add(req.newFetchPersonAppDataRequest('OWNER', 'azubisterTestResults'), 'data');
	req.add(req.newFetchPersonAppDataRequest('OWNER', 'answers'), 'data');
	req.send(onLoadResultData);
}


function initResults() {
	loadResultData();
}
